package net.togogo.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect
@Component
public class LogAspect {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //日志记录切面
    @Pointcut("execution(* net.togogo.web..*.*(..))")
    public void log(){}

    //执行之前开始记录
    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURI().toString();
        String ip = request.getLocalAddr();
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        RequestLog requestLog = new RequestLog(url,ip,classMethod,args);
        logger.info("request:{},",requestLog);
    }

    //执行之后
    @After("log()")
    public void doafter(){
        logger.info("=========================doafter=========================");
    }

    //执行之后 将日志保存在result里面
    @AfterReturning(returning = "result",pointcut = "log()")
    public void doafterReturn(Object result){
        logger.info("result:{}",result);
    }

    /**
     * 获取需要记录的参数
     * url 访问的路径
     * ip 访问的ip
     * classMethod 执行了得类的方法
     * args 输入的参数
     */

    public class RequestLog{
        private String url;
        private String ip;
        private String classMethod;
        private Object[] agrs;

        public RequestLog(String url, String ip, String classMethod, Object[] agrs) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.agrs = agrs;
        }

        @Override
        public String toString() {
            return "RequestLog{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", agrs=" + Arrays.toString(agrs) +
                    '}';
        }
    }

}
